package com.kingbook.core.result;

import com.alibaba.fastjson.JSONArray;
import com.kingbook.common.utils.CollectionUtils;
import com.kingbook.core.enums.ResultCode;
import com.google.common.collect.Lists;

import java.lang.reflect.Array;
import java.util.Collection;

import static com.kingbook.core.enums.ResultCode.FAILED;
import static com.kingbook.core.enums.ResultCode.SUCCESS;

/**
 * @Author: Bucky
 * @Date: 2019/1/2
 * @Version 1.0
 */
public class JSONPageResult extends JSONResult {

    protected static final long serialVersionUID = 1547550418291759035L;

    private int pageNo;

    private int pageSize;

    private int rows;

    private JSONPageResult(ResultCode code, String msg, int pageNo, int pageSize, int rows, JSONArray data) {
        super(code, msg, data);
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.rows = rows;
    }

    public static JSONPageResult success(int pageNo, int pageSize, int rows, Object obj) {
        JSONArray ja = new JSONArray();
        if (obj != null) {
            if (Collection.class.isInstance(obj)) {
                Collection<?> c = (Collection<?>) obj;
                if (!CollectionUtils.isEmpty(c)) {
                    ja.addAll(c);
                }
            } else if (obj.getClass().isArray() && Array.getLength(obj) > 0) {
                ja.addAll(Lists.newArrayList((Object[]) obj));
            } else {
                ja.add(obj);
            }
        }
        return new JSONPageResult(SUCCESS, "", pageNo, pageSize, rows, ja);
    }

    public static JSONPageResult success(int pageNo, int pageSize, int rows, int count, JSONArray data) {
        return new JSONPageResult(SUCCESS, "", pageNo, pageSize, rows, data);
    }

    public static JSONPageResult failed(ResultCode code, String msg) {
        return new JSONPageResult(code, msg, 0, 0, 0, new JSONArray());
    }

    public static JSONPageResult failed(String msg) {
        return JSONPageResult.failed(FAILED, msg);
    }


    public int getPageNo() {
        return pageNo;
    }

    public int getPageSize() {
        return pageSize;
    }

    public int getRows() {
        return rows;
    }

    public int getPages() {
        if (rows > 0) {
            return rows / pageSize + (rows % pageSize == 0 ? 0 : 1);
        }
        return 0;
    }

    @Override
    public JSONArray getData() {
        return data;
    }

}
